package com.yuan.controller;

import com.yuan.enums.ResponseEnum;
import com.yuan.exception.UnauthorizedException;
import com.yuan.vo.ResponseVO;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一异常处理
 *
 * @Author yuan
 * @Date 2021/5/31 16:20
 */
@RestControllerAdvice
public class ExceptionController {
    /**
     * 捕获shiro异常
     *
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    public ResponseVO handle401(ShiroException e) {
        return ResponseVO.error(ResponseEnum.UNAUTHORIZED);
    }

    /**
     * 捕获自定义UnauthorizedException异常
     * TODO也可以返回指定状态码
     * @return
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthorizedException.class)
    public ResponseVO handle401() {
        return ResponseVO.error(ResponseEnum.UNAUTHORIZED);
    }

    /**
     * 捕获全局异常
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseVO globalException(HttpServletRequest request, Throwable ex) {
        return ResponseVO.error(ResponseEnum.INTERNAL_SERVER_ERROR);
    }

    /**
     * 获取请求中code
     * @param request
     * @return
     */
    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}
